<?php

namespace App\Http\Controllers;

use App\Business\BLL\ChallengeGameBLL;
use App\Business\BLL\LuckMoneyBLL;
use App\Business\BLL\Personal;
use App\Business\BLL\SectBLL;
use App\Business\BLL\SettlementBLL;
use App\Jobs\SendResetScoreMsg;
use App\Models\ChallengeGame;
use App\Models\LuckMoneyLog;
use App\Models\LuckMoneyRule;
use App\Models\WechatUser;
use Illuminate\Http\Request;

class ChallengeGameController extends Controller
{
    function list() {
        $pn = request()->input('pn', config('api.page_num'));
        $city = request()->input('city', '');
        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city .= '%';

        $column = ['challenge_games.id',
            'usera.name as usera_name',
            'usera.nickname as usera_nickname',
            'usera.head_img as usera_head_img',
            'userb.name as userb_name',
            'userb.nickname as userb_nickname',
            'userb.head_img as userb_head_img',
            'challenge_games.game_datetime',
            'challenge_games.type',
            'challenge_games.status',
            'challenge_games.view',
            'challenge_games.score_a',
            'challenge_games.score_b'
        ];
        $list = ChallengeGame::join('wechat_users as usera', function ($join) {
            $join->on('challenge_games.play_a', '=', 'usera.id');
        })
            ->join('wechat_users as userb', function ($join) {
                $join->on('challenge_games.play_b', '=', 'userb.id');
            })
            ->where('challenge_games.city', 'like', $city)
            ->orderBy('game_datetime', 'desc')
            ->paginate($pn, $column);
        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }

    public function info()
    {
        $column = ['challenge_games.id',
            'usera.id as usera_id',
            'usera.name as usera_name',
            'usera.nickname as usera_nickname',
            'usera.head_img as usera_head_img',
            'usera.point as usera_point',
            'userb.id as userb_id',
            'userb.name as userb_name',
            'userb.nickname as userb_nickname',
            'userb.head_img as userb_head_img',
            'userb.point as userb_point',
            'challenge_games.game_datetime',
            'challenge_games.score_a',
            'challenge_games.score_b',
            'challenge_games.type',
            'challenge_games.status',
        ];

        $id = request()->input('game_id', 0);
        $geme = ChallengeGame::find($id);
        if ($geme) {
            $geme->view += 1;
            $geme->save();
        } else {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }

        $game = ChallengeGame::join('wechat_users as usera', function ($join) {
            $join->on('challenge_games.play_a', '=', 'usera.id');
        })
            ->join('wechat_users as userb', function ($join) {
                $join->on('challenge_games.play_b', '=', 'userb.id');
            })
            ->where('challenge_games.id', $id)
            ->select($column)
            ->first();

        if ($game) {
            //查询红包
            $luckMoney = LuckMoneyLog::where('game_id', $game->id)->latest()->first();
            //查新显示语句
            $lmDisplay = "获得了乒乓江湖";
            if ($luckMoney) {
                $rule = LuckMoneyRule::find($luckMoney->rule_id);
                $lmDisplay = $rule->desc;
            }
            return response()->json(['recode' => 1, 'info' => $game, 'luckmoney' => $luckMoney, 'lm_display' => $lmDisplay]);
        } else {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }
    }

    public function startGame()
    {
        $playA = request()->input('play_a', 0);
        $type = request()->input('type', 1);
        $playB = request()->input('play_b', 0);
        $city = request()->input('city', 110000);
        //如果用户地址信息为空保存手动选择的地址
        $wechatUser = WechatUser::where('id', $playA)
            ->first();
        if (empty($wechatUser->city)){
            $wechatUser->city=$city;
            $wechatUser->save();
        }

        if ($type == 1) {
            $playABLL = new Personal($playA);
            $playBBLL = new Personal($playB);
        } else {
            $playABLL = new SectBLL($playA);
            $playBBLL = new SectBLL($playB);
        }
        $challengeGame = new ChallengeGameBLL;
        $res = $challengeGame->startGame($playABLL, $playBBLL, $type);

        if ($res['status']) {
            return response()->json(['recode' => 1, 'id' => $res['id'], 'msg' => $res['msg']]);
        } else {
            return response()->json(['recode' => 0, 'msg' => $res['msg']]);
        }

    }

    public function myGamePerson()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $sectId = request()->input('sect_id', 0);
        $userId = request()->input('user_id', 0);
        $sort = request()->input('sort', 'desc');
        $status = request()->input('status', null);

        $column = ['challenge_games.id',
            'usera.name as usera_name',
            'usera.nickname as usera_nickname',
            'usera.head_img as usera_head_img',
            'userb.name as userb_name',
            'userb.nickname as userb_nickname',
            'userb.head_img as userb_head_img',
            'challenge_games.game_datetime',
            'challenge_games.type',
            'challenge_games.status',
            'challenge_games.view',
            'challenge_games.score_a',
            'challenge_games.score_b',
            'challenge_games.play_a',
            'challenge_games.play_b',
        ];

        if ($sectId) {
            $list = ChallengeGame::join('wechat_users as usera', function ($join) {
                $join->on('challenge_games.play_a', '=', 'usera.id');
            })
                ->join('wechat_users as userb', function ($join) {
                    $join->on('challenge_games.play_b', '=', 'userb.id');
                })
                ->where('status', '!=', 0)
                ->whereRaw("(challenge_games.type = 1 and (play_a=$userId or play_b=$userId)) or (challenge_games.type = 2 and (play_a=$sectId or play_b=$sectId))");

        } else {
            $list = ChallengeGame::join('wechat_users as usera', 'challenge_games.play_a', '=', 'usera.id')
                ->leftJoin('wechat_users as userb', 'challenge_games.play_b', '=', 'userb.id')
                ->where([['type', 1], ['status', '!=', 0]])
                ->where(function ($query) use ($userId) {
                    $query->orWhere('play_a', '=', $userId)
                        ->orWhere('play_b', '=', $userId);
                });
        }

        if ($status) {
            $list = $list->where('status', $status);
        }

        $list = $list->orderBy('game_datetime', $sort)
            ->paginate($pn, $column);

        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }

    public function setScore()
    {
        $gameId = request()->input('game_id', 0);
        $scoreA = request()->input('score_a', 0);
        $scoreB = request()->input('score_b', 0);

        $scoreA = is_null($scoreA) ? 0 : $scoreA;
        $scoreB = is_null($scoreB) ? 0 : $scoreB;

        if ($scoreA == $scoreB) {
            return response()->json(['recode' => 0, 'msg' => '比分错误']);
        }

        $game = ChallengeGame::find($gameId);
        if (!$game || $game->status != 10) {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }
        $game->score_a = $scoreA;
        $game->score_b = $scoreB;
        $game->status = 20;

        \DB::transaction(function () use ($game) {
            //保存比分
            $game->save();
            $settlement = new SettlementBLL;
            $settlement->settlement($game);
        });

        $luckmoneyBLL = new LuckMoneyBLL;
        $luckMoney = $luckmoneyBLL->getLuckMoney($game);

        return response()->json(['recode' => 1, 'luckmoney' => $luckMoney, 'msg' => '保存成功']);
    }

    public function resetScore()
    {
        $gameId = request()->input('game_id', 0);
        $scoreA = request()->input('score_a', 0);
        $scoreB = request()->input('score_b', 0);
        if ($scoreA == 0 && $scoreB == 0) {
            return response()->json(['recode' => 0, 'msg' => '比分错误']);
        }

        $game = ChallengeGame::find($gameId);
        if (!$game || $game->status != 30) {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }
        $oldScoreA = $game->score_a;
        $oldScoreB = $game->score_b;
        $game->score_a = $scoreA;
        $game->score_b = $scoreB;
        $game->status = 20;

        \DB::transaction(function () use ($game, $oldScoreA, $oldScoreB) {
            //保存比分
            $game->save();
            $settlement = new SettlementBLL;
            $settlement->resettlement($game, $oldScoreA, $oldScoreB);
        });

        $luckMoney = ['recode' => 20, 'msg' => '当前没有红包'];

        return response()->json(['recode' => 1, 'luckmoney' => $luckMoney, 'msg' => '保存成功']);
    }

    public function setAbnormal()
    {
        $gameId = request()->input('game_id', 0);
        $game = ChallengeGame::find($gameId);
        if (!$game || $game->status != 20) {
            return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
        }
        $game->status = 30;
        $game->save();
        //发送通知
        $this->dispatch((new SendResetScoreMsg($game)));

        return response()->json(['recode' => 1, 'msg' => '提交成功']);

    }

    public function hasGame()
    {
        $id = request()->input('id', '');
        //查询是否有比赛
        $game = ChallengeGame::where([['type', 1], ['play_a', $id]])
            ->where(function ($query) {
                $query->where('status', 10)
                    ->orWhere('status', 30);
            })
            ->first();
        if ($game) {
            return response()->json(['recode' => 1, 'id' => $game->id, 'msg' => '存在比赛']);
        }
        return response()->json(['recode' => 0, 'id' => 0, 'msg' => '不存在比赛']);
    }

    // public function cancelGame()
    // {
    //     $gameId = request()->input('game_id', 0);
    //     $game = ChallengeGame::find($gameId);
    //     if (!$game || $game->status != 10) {
    //         return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
    //     }
    //     $game->status = 0;
    //     $game->save();
    //     return response()->json(['recode' => 1, 'msg' => '取消成功']);

    // }

    // public function rejectGame()
    // {
    //     $gameId = request()->input('game_id', 0);
    //     $game = ChallengeGame::find($gameId);
    //     if (!$game || $game->status != 10) {
    //         return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
    //     }
    //     $game->status = 60;
    //     $game->save();
    //     return response()->json(['recode' => 1, 'msg' => '拒绝成功']);

    // }
    // public function applyGame()
    // {
    //     $gameId = request()->input('game_id', 0);
    //     $applyId = request()->input('apply_id', 0);
    //     $game = ChallengeGame::find($gameId);
    //     if (!$game || $game->status != 10) {
    //         return response()->json(['recode' => 0, 'msg' => '未找到比赛']);
    //     }
    //     if ($game->type == 1) {
    //         $applyBLL = new Personal($applyId);
    //     } else {

    //     }
    //     if ($applyBLL->verification()) {
    //         $game->play_b = $applyBLL->id;
    //     } else {
    //         return response()->json(['recode' => 0, 'msg' => '应战者不存在']);
    //     }
    //     $game->status = 20;
    //     $game->save();
    //     return response()->json(['recode' => 1, 'msg' => '应战成功']);
    // }
}
